<template>
    <div>
        <el-form class="studentBox" ref="studentFormRef" :model="updateStudent" :rules="rules" label-width="100px"
            label-postition="right">
            <el-form-item label="学生姓名" prop="name">
                <el-input v-model="updateStudent.name" />
            </el-form-item>
            <el-form-item label="学生性别" prop="gender">
                <el-select v-model="updateStudent.gender" placeholder="请选择学生性别">
                    <el-option v-for="item in genderOPtions" :label="item.name" :value="item._id" :key="item._id" />
                </el-select>
            </el-form-item>
            <el-form-item label="学校" prop="school">
                <el-autocomplete v-model="updateStudent.school" :fetch-suggestions="querySearchSchool" clearable
                    class="w-50" placeholder="请输入所在学校" />
            </el-form-item>
            <el-form-item label="专业" prop="major">
                <el-autocomplete v-model="updateStudent.major" :fetch-suggestions="querySearchMajor" clearable
                    class="w-50" placeholder="请输入所选专业" />
            </el-form-item>
            <el-form-item label="年级" prop="grade">
                <el-select v-model="updateStudent.grade" placeholder="请选择年级">
                    <el-option v-for="item in gradeOPtions" :label="item.name" :value="item._id" :key="item._id" />
                </el-select>
            </el-form-item>
            <el-form-item label="学历" prop="education">
                <el-select v-model="updateStudent.education" placeholder="请选择学历">
                    <el-option v-for="item in educationOPtions" :label="item.name" :value="item._id" :key="item._id" />
                </el-select>
            </el-form-item>
            <el-form-item label="学习方向" prop="direction">
                <el-select v-model="updateStudent.direction" placeholder="请选择学习方向">
                    <el-option v-for="item in directionOPtions" :label="item.name" :value="item._id" :key="item._id" />
                </el-select>
            </el-form-item>
            <el-form-item label="身份号码" prop="id_number">
                <el-input v-model="updateStudent.id_number" />
            </el-form-item>
            <el-form-item label="电话号码" prop="phone">
                <el-input v-model="updateStudent.phone" />
            </el-form-item>
            <el-form-item label="家长姓名" prop="parent">
                <el-input v-model="updateStudent.parent" />
            </el-form-item>
            <el-form-item label="家长联系电话" prop="parent_phone">
                <el-input v-model="updateStudent.parent_phone" />
            </el-form-item>
            <el-form-item label="家庭住址" prop="address">
                <el-input v-model="updateStudent.address" />
            </el-form-item>
            <el-form-item label="QQ号码" prop="qq">
                <el-input v-model="updateStudent.qq" />
            </el-form-item>
            <el-form-item label="所在班级" prop="class">
                <el-select v-model="updateStudent.class" placeholder="请选择所在班级">
                    <el-option v-for="item in classOptions" :label="item.classname" :value="item._id" :key="item._id" />
                </el-select>
            </el-form-item>
            <el-form-item label="入学时间" prop="admission_date">
                <el-date-picker v-model="updateStudent.admission_date" type="date" placeholder="请选择入学时间"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="授课教师" prop="teacher_id">
                <el-select v-model="updateStudent.teacher_id" placeholder="请选择授课教师">
                    <el-option v-for="item in teacherOPtions" :label="item.name" :value="item._id" :key="item._id" />
                </el-select>
            </el-form-item>
            <el-form-item label="学管" prop="manager_id">
                <el-select v-model="updateStudent.manager_id" placeholder="请选择学管">
                    <el-option v-for="item in manageOptions" :label="item.name" :value="item._id" :key="item._id" />
                </el-select>
            </el-form-item>
            <el-form-item label="照片" prop="pictures">
                <el-upload :action="baseApi + '/manage/img/upload'" list-type="picture-card" :auto-upload="true"
                    name="image" accept="image/*" :file-list="fileList" :on-change="handleChange">
                    <el-icon>
                        <Plus />
                    </el-icon>

                    <template #file="{ file }">
                        <div>
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                            <span class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                    <el-icon><zoom-in /></el-icon>
                                </span>
                                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </span>


                            </span>
                        </div>
                    </template>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>

            </el-form-item>
            <el-form-item label="备注信息" prop="note">
                <el-form-item label-="备注" prop="note">
                    <Editor v-model="updateStudent.note" :api-key="tiny.apiKey" :init="tiny.init"/>
                </el-form-item>
            </el-form-item>
            <el-form-item>
                <el-button type="primary"
                    @click="updateStudent._id == null ? addData(studentFormRef) : updateData(studentFormRef)">确定</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup lang="ts">
import type { classInfoData } from '@/api/class/type';
import type { roleInforDate } from '@/api/role/type';
import type { studentInfoData } from '@/api/student/type';
import type { userInfoData } from '@/api/user/type';
import useClassStore from '@/store/modules/class';
import useMajorStore from '@/store/modules/major';
import useRoleStore from '@/store/modules/role';
import useSchoolStore from '@/store/modules/school';
import useUserStore from '@/store/modules/user';
import type { FormInstance, FormRules, UploadFile, UploadProps } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';

const studentFormRef = ref();
const updateStudent = ref<studentInfoData>({
    _id: null,
    name: '', //姓名
    gender: '',//性别
    school: '', //学校
    major: '',//专业
    grade: '', //年级
    education: '', //学历
    direction: '',//学习方向
    id_number: '',//身份号码
    phone: '',//电话号码
    parent: '',//家长姓名
    parent_phone: '', //家长联系电话
    address: '',//家庭住址
    qq: '', //QQ号码
    class: '',//所在班级
    admission_date: '', //入学时间
    teacher_id: '', //教师id
    manager_id: '',//学管id
    pictures: [],//照片数组
    note: '',//备注信息
})
const ValidatePhone = (_rules: any, value: any, callback: any) => {
  value = value.trim();

  // 正则表达式
  const reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
  if (value === "") {
    callback(new Error("请输入电话号码"));
  } else if (!reg.test(value)) {
    callback(new Error("请输入正确的电话号码"));
  } else {
    callback();
  }
}
// 身份证
const ValidateIdNumber= (_rules: any, value: any, callback: any) => {
  value = value.trim();

  // 正则表达式
        const _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
        const _IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
  if (value === "") {
    callback(new Error("请输入身份证号码"));
  } else if (_IDRe18.test(value) || _IDre15.test(value)) {
      callback();
} else {
    callback(new Error("请输入正确的身份证号码"));
  }
}

const rules = reactive<FormRules>({
  name: [{required:true,message:"请输入姓名",trigger:'blur'}],
  gender: [{required:true,message:"请选择性别",trigger:'blur'}],
  direction: [{required:true,message:"请选择学习方向",trigger:'blur'}],
  id_number: [{required:true,validator:ValidateIdNumber ,trigger:'blur'}],
  phone: [{required:true, validator: ValidatePhone,trigger:'blur'}],
  class: [{required:true,message:"请选择班级",trigger:'blur'}],
  admission_date: [{required:true,message:"请选择入学时间",trigger:'blur'}],
  teacher_id: [{required:true,message:"请选择授课教师",trigger:'blur'}],
  manager_id: [{required:true,message:"请选择学管",trigger:'blur'}],
})
import { useRoute, useRouter } from 'vue-router';
const $route=useRoute()
const $router = useRouter()
import useStudentStore from '@/store/modules/student';
const studentStore=useStudentStore()

const addData = async (FormEl: FormInstance | undefined) => {
    if (!FormEl) return
    await FormEl.validate((valid, fields) => {
        if (valid) {
            // @ts-ignore
           updateStudent.value.pictures = getImgs();
           studentStore.addStudent((updateStudent.value as studentInfoData)).then(response=>{
            $router.replace("/student")
           })
        } else {
            console.log("error submit!", fields);
        }
    })
}
const updateData = async (FormEl: FormInstance | undefined) => {
    if (!FormEl) return
    await FormEl.validate((valid, fields) => {
        if (valid) {
           updateStudent.value.pictures = getImgs()
         studentStore.upDataStudent(updateStudent.value).then((response)=>{
            $router.replace('/student')
         })  
        }else {
            console.log("error submit!", fields);
        }
    })
}

// 格式化
const roleStore = useRoleStore()
const userStore = useUserStore()
const classstore = useClassStore()
const schoolStore = useSchoolStore()
const majorStore = useMajorStore()
// 教师id
const teacher_role_id = ref('');
// 学管id
const manager_role_id = ref('');
// 角色数组
const roleOptions = ref<roleInforDate[]>([]);
// 用户数组
const userOptions = ref<userInfoData[]>([]);
// 班级数组
const classOptions = ref<classInfoData[]>([])
// 教师数组
const teacherOPtions = ref<userInfoData[]>([]);
// 学管数组
const manageOptions = ref<userInfoData[]>([]);
// 学校数组
const schoolOptions = ref<userInfoData[]>([])
// 专业数组
const majorOptions = ref<userInfoData[]>([])
// 性别/年纪/学历/学习方向数据类型
interface filterData {
    _id: string,
    name: string
}
// 性别数据列表
const genderOPtions = ref<filterData[]>([
    { _id: '0', name: '男' },
    { _id: '1', name: '女' }
])
// 年祭数据列表
const gradeOPtions = ref<filterData[]>([
    { _id: '1', name: '大一' },
    { _id: '2', name: '大二' },
    { _id: '3', name: '大三' },
    { _id: '4', name: '大四' },
    { _id: '5', name: '在读研究生' },
])
// 学历数据列表
const educationOPtions = ref<filterData[]>([
    { _id: '1', name: '专科' },
    { _id: '2', name: '本科' },
    { _id: '3', name: '硕士' },
    { _id: '4', name: '社会' },
])
// 学习方向数据列表
const directionOPtions = ref<filterData[]>([
    { _id: '1', name: 'web前端' },
    { _id: '2', name: 'Java' },
    { _id: '3', name: 'C/C++' },
    { _id: '4', name: '直播电商' },
    { _id: '5', name: '少儿编程' },
    { _id: '6', name: '嵌入式' },
    { _id: '7', name: '导弹维修' },
])
// 获取班级列表
const getClassList = () => {
    return new Promise((resolve, _reject) => {
        if (classstore.classes && classstore.classes.length) {
            classOptions.value = classstore.classes;

            resolve(true)
        } else {

            classstore.getClassAll().then(() => {
                // @ts-ignore
                classOptions.value = classstore.classes;

                resolve(true)
            })
        }
    })
}
// 获取学校列表
const getSchoolList = () => {
    return new Promise((resolve, _reject) => {
        if (schoolStore.schools && schoolStore.schools.length) {
            // @ts-ignore
            schoolOptions.value = schoolStore.schools;
            resolve(true)
        } else {
            schoolStore.getSchoolAll().then(() => {
                // @ts-ignore
                schoolOptions.value = schoolStore.schools;
                resolve(true)
            })
        }
    })
}
// 获取专业列表
const getMajorList = () => {
    return new Promise((resolve, _reject) => {
        if (majorStore.majors && majorStore.majors.length) {
            // @ts-ignore
            majorOptions.value = majorStore.majors;
            resolve(true)
        } else {
            majorStore.getMajorAll().then(() => {
                // @ts-ignore
                majorOptions.value = majorStore.majors;
                resolve(true)
            })
        }
    })
}
// 获取角色数组
const getRoleList = () => {
    return new Promise((resolve, _reject) => {
        if (roleStore.roles && roleStore.roles.length) {
            roleOptions.value = roleStore.roles;
            roleOptions.value.forEach((item) => {
                if (item.name == "教师") {


                    teacher_role_id.value = item._id as string

                } else if (item.name == "学管") {
                    manager_role_id.value = item._id as string

                }

            });
            resolve(true)
        } else {

            roleStore.getRoleList().then(() => {
                // @ts-ignore
                roleOptions.value = roleStore.roles;
                roleOptions.value.forEach((item) => {
                    if (item.name == "教师") {
                        teacher_role_id.value = item._id as string
                    } else if (item.name == "学管") {
                        manager_role_id.value = item._id as string
                    }
                })
                resolve(true)
            })
        }
    })
}
// 获取用户数组
const getUserList = () => {

    return new Promise((resolve, _reject) => {

        if (userStore.users && userStore.users.length) {
            userOptions.value = userStore.users

            userOptions.value.forEach((item) => {
                if (item.role_id == teacher_role_id.value) {
                    teacherOPtions.value.push(item);
                } else if (item.role_id == manager_role_id.value) {
                    manageOptions.value.push(item)
                }
            })
            resolve(true)
        } else {
            userStore.getUserAll().then(() => {
                userOptions.value = userStore.users
                userOptions.value.forEach((item) => {

                    if (item.role_id == teacher_role_id.value) {
                        teacherOPtions.value.push(item);
                        console.log('userOptions.value', teacherOPtions.value);
                    } else if (item.role_id == manager_role_id.value) {
                        manageOptions.value.push(item)
                    }
                })
            })
            resolve(true)
        }
    })
}

const querySearchSchool = (queryString: string, cb: any) => {
    // @ts-ignore
    schoolOptions.value.forEach(item => item.value = item.schoolname)
    const results = queryString
        ? schoolOptions.value.filter(createFilter(queryString))
        : schoolOptions.value
    // call callback function to return suggestions
    cb(results)
}
const querySearchMajor = (queryString: string, cb: any) => {
    // @ts-ignore
    majorOptions.value.forEach(item => item.value = item.majorname)
    const results = queryString
        ? majorOptions.value.filter(createFilter(queryString))
        : majorOptions.value
    // call callback function to return suggestions
    cb(results)
}
const createFilter = (queryString: string) => {
    return (restaurant: any) => {
        return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
    }
}
// 关于图片上传
// 请求标识
const baseUrl = import.meta.env.VITE_APP_SERVICE_URL
const baseApi = import.meta.env.VITE_APP_BASE_API
// 引入自己封装的axios对象，用于图片的删除
import request from '@/utils/request';

const handleChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
    console.log('uploadFile', uploadFile);
    // 本地上传完成
    if (uploadFile.status == "success") {
        const result = uploadFile.response
        // 是否上传给服务器
        // @ts-ignore
        if (result.status == 0) {
            // 取出服务器相应的图片名称和url地址
            // @ts-ignore
            const { name, url } = result.data
            uploadFile = uploadFiles[uploadFiles.length - 1];
            uploadFile.name = name;
            uploadFile.url = url
        }
    }
    // 记录已经上传的图片
    // @ts-ignore
    fileList.value = uploadFiles
}

const dialogImageUrl = ref("")
const dialogVisible = ref(false)
const disabled = ref(false)
// 已上传的图片数组
const fileList = ref<UploadFile[]>([])
const handleRemove = (file: UploadFile) => {
    request.post<any, any>('/manage/img/delete', { name: file.name }).then(response => {
        if (response.status == 0) {
            fileList.value.splice(fileList.value.indexOf(file), 1)
        }
    })
}
const handlePictureCardPreview = (file: UploadFile) => {
    // @ts-ignore
    dialogImageUrl.value = file.url;
    dialogVisible.value = true;
}
// 获取所有已经上传过的照片名称
const getImgs = () => {
    return fileList.value.map(item => item.name)
}

/* ----------------富文本相关内容------------------------- */
import Editor from "@tinymce/tinymce-vue";
const tiny = reactive({
    apiKey: "w8593t1vo6t8c9rf9zdr5m40p28g9j790kfdk0lema1vq658",
    init: {
        toolbar_mode: 'sliding',
        plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount checklist mediaembed casechange export formatpainter pageembed linkchecker a11ychecker tinymcespellchecker permanentpen powerpaste advtable advcode editimage advtemplate ai mentions tinycomments tableofcontents footnotes mergetags autocorrect typography inlinecss',
        toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table mergetags | addcomment showcomments | spellcheckdialog a11ycheck typography | align lineheight | checklist numlist bullist indent outdent | emoticons charmap | removeformat',
        tinycomments_mode: 'embedded',
        tinycomments_author: 'Author name',
        mergetags_list: [
            { value: 'First.Name', title: 'First Name' },
            { value: 'Email', title: 'Email' },
        ],
        ai_request: (_request:any, respondWith:any) => respondWith.string(() => Promise.reject("See docs to implement AI Assistant")),
    },
});
// 获取要编辑的学生数据
const getStudent =()=>{
    // 从路由对象中取出要编辑的学员_id
    const{_id} = $route.params
    
        studentStore.getStudentById(_id as string).then(response=>{
            updateStudent.value = response as studentInfoData
            const {pictures} = response as studentInfoData
            console.log('pictures',pictures);
            
            if(pictures && pictures.length !=0){
                // @ts-ignore
                fileList.value = pictures.map(item=>{
                    return{
 
                        name:item,
                        url:baseApi +'/upload/'+item
                    }
                })
            }
        })
    }

onMounted(() => {
    getRoleList().then(() => {
        getUserList().then(() => {
            Promise.all([getClassList(),
            getMajorList(),
            getSchoolList()]).then(()=>{
                getStudent()
            })
            
        })
    })
})
</script>

<style scoped></style>